﻿namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Net.Mime;
    using System.Text;
    using System.Web.Mvc;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;

    public sealed class JsonSerializationResult : ContentResult
    {
        public JsonSerializationResult()
            : this("application/json", null as object)
        {
        }

        public JsonSerializationResult(string contentType, object model)
        {
            if (null == contentType)
            {
                throw new ArgumentNullException("contentType");
            }
            else if (0 == contentType.Length)
            {
                throw new ArgumentOutOfRangeException("contentType");
            }

            this.ContentEncoding = Encoding.UTF8;
            this.ContentType = new ContentType(contentType).MediaType;
            if (null != model)
            {
                this.Content = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            base.ExecuteResult(context);
        }
    }
}